package com.ys.web.user.complain.service.impl;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.IdUtil;
import com.ys.base.BaseConstants;
import com.ys.base.EnumType;
import com.ys.utils.base.http.McodeHandler;
import com.ys.utils.base.j2se.DateUtil;
import com.ys.utils.base.j2se.StringHandler;
import com.ys.utils.help.GroupUtils;
import com.ys.utils.help.UserUtils;
import com.ys.utils.redis.Redis;
import com.ys.utils.redis.key.GroupKey;
import com.ys.utils.spring.config.SystemError;
import com.ys.utils.spring.properties.Config;
import com.ys.web.sys.notice.mapper.SystemNoticeMapper;
import com.ys.web.sys.notice.vo.SystemNoticeVo;
import com.ys.web.user.complain.mapper.ComplainMapper;
import com.ys.web.user.complain.po.ComplainPO;
import com.ys.web.user.complain.service.ComplainService;
import com.ys.web.user.login.LoginInfo;
import com.ys.web.user.login.LoginService;
import com.ys.web.ws.bean.MessageResponseBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author quxinjun
 * @version 1.0.0
 * @ClassName ComplainServiceImpl.java
 * @Description 投诉实现类
 * @createTime 2021年05月24日 10:41:00
 */
@Slf4j
@Service
public class ComplainServiceImpl implements ComplainService {

    @Autowired
    private ComplainMapper complainMapper;

    @Autowired
    private SystemNoticeMapper systemNoticeMapper;

    @Autowired
    private LoginService loginService;

    @Override
    public List<Map<String, Object>> getCauseList() {
        return EnumType.ComplainCode.getAll();
    }

    @Override
    public void addComplain(Long uid, ComplainPO complainPO) {
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern(BaseConstants.BASE_FORMAT));
        if (complainPO.getType() == 2) {
            //验证操作人是否在群里面
            Boolean flag = GroupUtils.isInGroup(String.valueOf(complainPO.getObjId()), String.valueOf(uid));
            if (!flag) {
                SystemError.wrapBs(EnumType.ResponseCode.Fail.getCode(), "您当前不在群组中，操作失败");
            }
        } else {
            complainPO.setObjId(String.valueOf(McodeHandler.from32Radix(complainPO.getObjId())));
        }
        LoginInfo loginInfo = loginService.infoByUid(StringHandler.getString(uid));
        complainPO.setPhone(StringHandler.isEmpty(loginInfo) ? complainPO.getPhone() : loginInfo.getPhone());
        complainPO.setCreateTime(time);
        complainPO.setIsDeal(false);
        int row = complainMapper.insertSelective(complainPO);


        ThreadUtil.execAsync(() -> {
            if (row > 0) {

                StringBuilder content = new StringBuilder();
                if (complainPO.getType() == 2) {
                    //群聊  通知内容
                    content
                            .append("<p>群聊投诉</p>")
                            .append("<p>投诉群名称   ：" + GroupUtils.getCacheGroupInfo(complainPO.getObjId()).getName() + "</p>")
                            .append("<p>投诉原因    ：" + complainPO.getCause() + "</p>")
                            .append("<p>投诉内容    ：" + complainPO.getContent() + "</p>")
                            .append("<p><font color='red'>温馨提示</font></p>")
                            .append("<p>" + Config.pp.getOrDefault(BaseConstants.DataSourceConstants.COMPLAIN_TIP_GROUP, "请规范使用本平台功能") + "</p>");
                } else {
                    //私聊  通知内容
                    content
                            .append("<p>私聊投诉</p>")
                            .append("<p>投诉原因    ：" + complainPO.getCause() + "</p>")
                            .append("<p>投诉内容    ：" + complainPO.getContent() + "</p>")
                            .append("<p><font color='red'>温馨提示</font></p>")
                            .append("<p>" + Config.pp.getOrDefault(BaseConstants.DataSourceConstants.COMPLAIN_TIP_SINGLE, "请规范使用本平台功能") + "</p>");
                }

                SystemNoticeVo systemNoticeVo = new SystemNoticeVo();
                systemNoticeVo.setId(IdUtil.randomUUID().replaceAll("-", ""));
                systemNoticeVo.setCreateTime(DateUtil.getDate(new Date(), BaseConstants.BASE_FORMAT));
                systemNoticeVo.setUserId(complainPO.getUserId());//回复对应的用户
                systemNoticeVo.setContent(content.toString());
                systemNoticeVo.setTitle("投诉通知");

                int i = systemNoticeMapper.addNotice(systemNoticeVo);


                String windowId = "SYS_NOTICE";
                MessageResponseBean messageResponseBean = new MessageResponseBean();

                messageResponseBean.setCode(EnumType.MessageCode.SYS_NOTICE.getCode());
                messageResponseBean.setFrom(windowId);
                messageResponseBean.setWindowId(windowId);
                messageResponseBean.setUserName("投诉通知");
                messageResponseBean.setAvatarUrl(UserUtils.SYS_NOTICE.getAvatarUrl());
                messageResponseBean.setData(systemNoticeVo.getContent());
                messageResponseBean.setMessageId(systemNoticeVo.getId());
                messageResponseBean.setCreateTime(systemNoticeVo.getCreateTime());

                if (i > 0) {
                    if (complainPO.getType() == 2) {
                        //推送 群中的管理员
                        Set<String> set = Redis.zSet.rangeByScore(GroupKey.groupMembersKey(complainPO.getObjId()), EnumType.GroupIdentity.MASTER.getCode().doubleValue(),
                                EnumType.GroupIdentity.MANAGER.getCode().doubleValue());
                        set.forEach(x -> {
                            GroupUtils.sendIfAbsent(messageResponseBean, StringHandler.getString(x), windowId);
                        });
                    } else {
                        //私聊推送
                        GroupUtils.sendIfAbsent(messageResponseBean, complainPO.getObjId(), windowId);
                    }
                }
            }
        });


    }

    @Override
    public List<ComplainPO> complainList(Long uid) {
        return complainMapper.complainList(uid);
    }

    @Override
    public int complainDel(Long uid, long complainId) {
        return complainMapper.complainDel(uid,complainId);
    }
}
